package com.strongbj.iot.devices.ru.response.handle;

import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.dam.message.MQMessageOfDAM;
import com.strongbj.iot.devices.dam.response.entity.SensorOfAwsPostdataEntity;
import com.strongbj.iot.devices.dam.response.entity.SensorParamesEntity;
import com.strongbj.iot.devices.ru.message.RUMessage;
import com.strongbj.iot.mq.producer.TopicSender;

import io.netty.channel.ChannelHandlerContext;

/**
 * 获取温度数据的处理
 * @author yuzhantao
 *
 */
public class GetTemperatureHandle  implements IMessageHandle<RUMessage,Object> {
	private static Logger logger = LogManager.getLogger(GetTemperatureHandle.class.getName());
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	private static final String ACTION_CODE = "realTimeDatas";
	private static final String DEV_TYPE="damDc";
	private static final String TOPIC="damRealTimeInfoToService";
	
	@Override
	public boolean isHandle(RUMessage t) {
		if(t.getType()==0x12){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, RUMessage t) {
		String json = this.getTemperature(t);
		topicSender.send(TOPIC, json);
		logger.info("发送温度信息到MQ完成:"+json);
		return null;
	}

	/**
	 * 获取6个传感器的温度数据
	 * @param message
	 * @return
	 */
	private String getTemperature(RUMessage message) {
		byte[] datas = message.getBody();
		List<SensorParamesEntity> sensorList = new ArrayList<>();
		for(int i=0;i<6;i++) {
			int temperature = ByteUtil.byteArrayToInt(datas,i*4);
			SensorParamesEntity spe = new SensorParamesEntity();
			spe.setSensorPosition(i+1);
			spe.setSensorType(1);
			spe.setSensorDatas(temperature);
			sensorList.add(spe);
		}
		
		for(int i=0;i<42;i++) {
			byte[] temp = new byte[2];
			System.arraycopy(datas, 24+i*2, temp, 0, 2);
			byte[] temp1 = new byte[] {temp[1],temp[0]};
			short temperature = ByteUtil.byteArrToShort(datas,24+i*2);
			System.out.println("pos:"+i+"   value:"+temperature+"   test:"+ByteUtil.byteArrToShort(temp1));
		}
		
		MQMessageOfDAM msg = new MQMessageOfDAM();
		msg.setActioncode(ACTION_CODE);
		
		SensorOfAwsPostdataEntity sensorOfAwsPostdataEntity=new SensorOfAwsPostdataEntity();
		sensorOfAwsPostdataEntity.setSensorList(sensorList);
		sensorOfAwsPostdataEntity.setRackConverCode(ByteUtil.byteArrToHexString(message.getAddress()));
		msg.setAwsPostdata(sensorOfAwsPostdataEntity);
		msg.setDevType(DEV_TYPE);
		msg.setTimestamp(System.currentTimeMillis());
		return JSON.toJSONString(msg);
	}
}
